import { Comment, Avatar, Form, Button, List, Input } from 'antd'

import { useState } from 'react'
import moment from 'moment'
const { TextArea } = Input

const CommentList = ({ comments }) => (
  <List
    dataSource={comments}
    header={`${comments.length} ${comments.length > 1 ? 'replies' : 'reply'}`}
    itemLayout='horizontal'
    renderItem={(props) => <Comment {...props} />}
  />
)

const Editor = ({ onChange, onSubmit, submitting, value }) => (
  <>
    <Form.Item>
      <TextArea rows={4} allowClear maxLength={200} onChange={onChange} value={value} />
    </Form.Item>
    <Form.Item>
      <Button htmlType='submit' loading={submitting} onClick={onSubmit} type='primary'>
        提交评论
      </Button>
    </Form.Item>
  </>
)

const AddComment = () => {
  const [comments, setComments] = useState([])
  const [submitting, setSubmitting] = useState(false)
  const [addValue, setAddValue] = useState('')

  const handleSubmit = () => {
    if (!addValue) {
      return
    }

    setSubmitting(true)

    setTimeout(() => {
      setComments([
        {
          author: 'Han Solo',
          avatar: 'https://zos.alipayobjects.com/rmsportal/ODTLcjxAfvqbxHnVXCYX.png',
          content: <p>{addValue}</p>,
          datetime: moment().fromNow()
        },
        ...comments
      ])
      setAddValue('')
      setSubmitting(false)
    }, 1000)
  }

  const handleChange = (e) => {
    setAddValue(e.target.value)
  }

  return (
    <>
      {comments.length > 0 && <CommentList comments={comments} />}
      <Comment
        avatar={<Avatar src='https://zos.alipayobjects.com/rmsportal/ODTLcjxAfvqbxHnVXCYX.png' alt='Han Solo' />}
        content={<Editor onChange={handleChange} onSubmit={handleSubmit} submitting={submitting} value={addValue} />}
      />
    </>
  )
}

export default AddComment
